import 'dart:async';
import 'xh_danmu_models.dart';

/// 弹幕数据项 - 传递自定义弹幕组件
class XhDanmuData {
  final String id;
  final XhDanmuComponent component; // 自定义弹幕组件
  final DateTime timestamp;

  XhDanmuData({
    required this.id,
    required this.component,
    DateTime? timestamp,
  }) : timestamp = timestamp ?? DateTime.now();

  @override
  String toString() {
    return 'XhDanmuData(id: $id, component: ${component.runtimeType}, timestamp: $timestamp)';
  }
}

/// 弹幕流管理器
class XhDanmuStreamController {
  // 内部流控制器
  final StreamController<XhDanmuData> _streamController = StreamController<XhDanmuData>.broadcast();

  // 弹幕数据流（对外只读）
  Stream<XhDanmuData> get stream => _streamController.stream;

  // 是否已关闭
  bool get isClosed => _streamController.isClosed;

  /// 添加单条弹幕
  void add(XhDanmuData danmuData) {
    if (!_streamController.isClosed) {
      _streamController.add(danmuData);
    }
  }

  /// 添加弹幕组件
  void addComponent(XhDanmuComponent component) {
    final danmuData = XhDanmuData(
      id: component.id,
      component: component,
    );
    add(danmuData);
  }

  /// 批量添加弹幕
  void addAll(List<XhDanmuData> danmuList) {
    for (final danmu in danmuList) {
      add(danmu);
    }
  }

  /// 添加错误
  void addError(Object error, [StackTrace? stackTrace]) {
    if (!_streamController.isClosed) {
      _streamController.addError(error, stackTrace);
    }
  }

  /// 关闭流
  Future<void> close() async {
    await _streamController.close();
  }

  /// 清空流中的数据（重新开始）
  void clear() {
    // 注意：StreamController.broadcast()不支持直接清空
    // 如果需要清空，需要重新创建StreamController
    // 这里提供一个标记方法，具体实现由使用者决定
  }
}

/// 弹幕数据源接口
abstract class XhDanmuDataSource {
  /// 获取弹幕数据流
  Stream<XhDanmuData> get stream;

  /// 开始监听数据源
  Future<void> start();

  /// 停止监听数据源
  Future<void> stop();

  /// 是否正在运行
  bool get isRunning;
}

/// WebSocket弹幕数据源示例
class XhDanmuWebSocketSource implements XhDanmuDataSource {
  final String url;
  final XhDanmuStreamController _controller = XhDanmuStreamController();
  StreamSubscription? _subscription;
  bool _isRunning = false;

  XhDanmuWebSocketSource(this.url);

  @override
  Stream<XhDanmuData> get stream => _controller.stream;

  @override
  bool get isRunning => _isRunning;

  @override
  Future<void> start() async {
    if (_isRunning) return;

    _isRunning = true;
    // 这里应该实现WebSocket连接逻辑
    // 示例代码：
    // final webSocket = await WebSocket.connect(url);
    // _subscription = webSocket.listen((data) {
    //   final map = jsonDecode(data);
    //   _controller.add(XhDanmuData.fromMap(map));
    // });
  }

  @override
  Future<void> stop() async {
    if (!_isRunning) return;

    _isRunning = false;
    await _subscription?.cancel();
    _subscription = null;
  }

  /// 手动添加数据（用于测试）
  void addTestData(XhDanmuData data) {
    _controller.add(data);
  }
}

/// 定时弹幕数据源示例
class XhDanmuTimerSource implements XhDanmuDataSource {
  final Duration interval;
  final List<String> texts;
  final XhDanmuStreamController _controller = XhDanmuStreamController();
  Timer? _timer;
  bool _isRunning = false;
  int _index = 0;

  XhDanmuTimerSource({
    required this.interval,
    required this.texts,
  });

  @override
  Stream<XhDanmuData> get stream => _controller.stream;

  @override
  bool get isRunning => _isRunning;

  @override
  Future<void> start() async {
    if (_isRunning || texts.isEmpty) return;

    _isRunning = true;
    _timer = Timer.periodic(interval, (timer) {
      // 注意：XhDanmuTimerSource 现在需要外部提供组件工厂方法
      throw UnsupportedError('XhDanmuTimerSource 需要外部提供组件实现，因为核心库不再包含具体组件');
    });
  }

  @override
  Future<void> stop() async {
    if (!_isRunning) return;

    _isRunning = false;
    _timer?.cancel();
    _timer = null;
  }
}

/// 数组弹幕数据源
class XhDanmuListSource implements XhDanmuDataSource {
  final List<XhDanmuData> data;
  final Duration interval;
  final XhDanmuStreamController _controller = XhDanmuStreamController();
  Timer? _timer;
  bool _isRunning = false;
  int _index = 0;

  XhDanmuListSource({
    required this.data,
    this.interval = const Duration(milliseconds: 1000),
  });

  @override
  Stream<XhDanmuData> get stream => _controller.stream;

  @override
  bool get isRunning => _isRunning;

  @override
  Future<void> start() async {
    if (_isRunning || data.isEmpty) return;

    _isRunning = true;
    _timer = Timer.periodic(interval, (timer) {
      if (_index < data.length) {
        _controller.add(data[_index]);
        _index++;
      } else {
        stop(); // 数据播放完毕，自动停止
      }
    });
  }

  @override
  Future<void> stop() async {
    if (!_isRunning) return;

    _isRunning = false;
    _timer?.cancel();
    _timer = null;
  }

  /// 重置播放位置
  void reset() {
    _index = 0;
  }
}

/// 混合弹幕数据源（支持多个数据源）
class XhDanmuMixedSource implements XhDanmuDataSource {
  final List<XhDanmuDataSource> sources;
  final XhDanmuStreamController _controller = XhDanmuStreamController();
  final List<StreamSubscription> _subscriptions = [];
  bool _isRunning = false;

  XhDanmuMixedSource(this.sources);

  @override
  Stream<XhDanmuData> get stream => _controller.stream;

  @override
  bool get isRunning => _isRunning;

  @override
  Future<void> start() async {
    if (_isRunning) return;

    _isRunning = true;

    // 订阅所有数据源
    for (final source in sources) {
      await source.start();
      final subscription = source.stream.listen(
        (data) => _controller.add(data),
        onError: (error) => _controller.addError(error),
      );
      _subscriptions.add(subscription);
    }
  }

  @override
  Future<void> stop() async {
    if (!_isRunning) return;

    _isRunning = false;

    // 取消所有订阅
    for (final subscription in _subscriptions) {
      await subscription.cancel();
    }
    _subscriptions.clear();

    // 停止所有数据源
    for (final source in sources) {
      await source.stop();
    }
  }
}
